/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: ToastUtils.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.baselib.utils;

import android.app.Activity;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.NotificationManagerCompat;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.widget.Toast;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import io.bhex.baselib.core.CApplication;

public class ToastUtils {
    //是否使用系统自带的Toast
    public static boolean useDefault = true;

    private static final String CHECK_OP_NO_THROW = "checkOpNoThrow";

    private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

    private static WeakReference<ToastProxy> toast;

    public static void Init(){
        //useDefault = isNotificationEnabled(CApplication.getInstance());

        NotificationManagerCompat manager = NotificationManagerCompat.from(CApplication.getInstance());
        // areNotificationsEnabled方法的有效性官方只最低支持到API 19，低于19的仍可调用此方法不过只会返回true，即默认为用户已经开启了通知。
        useDefault = manager.areNotificationsEnabled();

    }

    static {
        //useDefault = isNotificationEnabled(CApplication.getInstance());
    }

    private static void show(final Context context, final String message, final int duration) {
        if (context == null)
            return;

        if (TextUtils.isEmpty(message))
            return;

        if (Looper.myLooper() == Looper.getMainLooper()) {
            innerShow(context, message, duration);
        } else {
            //非UI线程的处理办法

            if (context instanceof Activity) {
                ((Activity) context).runOnUiThread(
                        new Runnable() {
                            @Override
                            public void run() {
                                innerShow(context, message, duration);
                            }
                        }
                );
            } else {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        innerShow(context, message, duration);
                    }
                });
            }
        }
    }

    public static void cancel() {
        if (toast != null && toast.get() != null)
            toast.get().cancel();
    }

    private static void innerShow(Context context, String message, int duration) {
        cancel();
        ToastProxy tmp = ToastProxy.makeText(context, message, duration);

        toast = new WeakReference<>(tmp);

        tmp.show();
    }

    /**
     * 长展示message{@link SuperToast}{@link SuperToast#LENGTH_LONG}
     *
     * @param context
     * @param message
     */
    public static void showLong(final Context context, final String message) {
        show(context, message, SuperToast.LENGTH_LONG);
    }

    public static void showLong(final String message) {
        show(CApplication.getInstance(), message, SuperToast.LENGTH_LONG);
    }

    /**
     * 短展示message{@link SuperToast}{@link SuperToast#LENGTH_SHORT}
     *
     * @param context
     * @param message
     */
    public static void showShort(final Context context, final String message) {
        show(context, message, SuperToast.LENGTH_SHORT);
    }

    public static void showShort(final String message) {
        show(CApplication.getInstance(), message, SuperToast.LENGTH_SHORT);
    }

    /**
     * 检测通知权限是否开启了，对于部分未开启权限的手机，可以考虑自己做一个window来模拟toast的显示
     *
     * @param context
     * @return
     */
    public static boolean isNotificationEnabled(Context context) {
        //4.1以前没有权限功能开关
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
            return true;

        //4.4以前不能对权限开启情况做检测，直接认为是关闭就好了
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
            return false;

        try {
            AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);

            ApplicationInfo appInfo = context.getApplicationInfo();

            String pkg = context.getApplicationContext().getPackageName();

            int uid = appInfo.uid;

            Class appOpsClass;


            appOpsClass = Class.forName(AppOpsManager.class.getName());

            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class);

            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
            int value = (int) opPostNotificationValue.get(Integer.class);

            return ((int) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

        } catch (Exception e) {
            DebugLog.e(e);
        }

        return false;

    }

    /**
     * 代理类，用于控制不同的Toast方案
     */
    static class ToastProxy {
        private Toast toast;
        public boolean bActivity = true;
        private SuperToast superToast;

        public ToastProxy(Toast toast) {
            this.toast = toast;
//            Display display = getWindowManager().getDefaultDisplay();
            // 获取屏幕高度
//            int height = display.getHeight();
//            this.toast.setGravity(Gravity.TOP, 0, height / 4);
            this.toast.setGravity(Gravity.CENTER, 0, 0);
        }

        public ToastProxy(SuperToast toast) {
            this.superToast = toast;
        }

        public static ToastProxy makeText(Context context, CharSequence text, int duration) {

            ToastProxy proxy = null;
            if (useDefault)
                proxy = new ToastProxy(Toast.makeText(context, text, duration));
            else if(context instanceof Activity) {
                proxy = new ToastProxy(SuperToast.makeText((Activity) context, text, duration));
                proxy.bActivity = true;
            }
            else {
                proxy = new ToastProxy(Toast.makeText(context, text, duration));
                proxy.bActivity = false;
            }
            return proxy;
        }

        public void show() {
            if (useDefault && toast !=null)
                toast.show();
            else if(bActivity == true && superToast != null)
                superToast.show();
            else if(toast !=null)
                toast.show();
        }

        public void cancel() {
            if (useDefault && toast !=null)
                toast.cancel();
            else if(bActivity == true && superToast != null)
                superToast.cancel();
            else if(toast !=null)
                toast.cancel();
        }
    }
}
